package video.com.service.impl;

import com.Exception.GlobalException;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.responseData.ResponseData;
import com.utils.GenerateNum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import video.com.aspect.FormatFileURL;
import video.com.entity.ChatRecord;
import video.com.entity.UserBehavior;
import video.com.mapper.ChatRecordMapper;
import video.com.mapper.UserBehaviorMapper;
import video.com.service.ChatRecordService;
import video.com.transition.VideoTransaction;
import video.com.transportEntity.vo.CommentPage;
import video.com.utils.StringUtil;
import video.com.utils.UserInfoUtils;

import javax.annotation.Resource;
import java.lang.reflect.Field;
import java.util.*;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author xwj
 * @since 2023-11-11
 */

@Slf4j
@Service
public class ChatRecordServiceImpl extends ServiceImpl<ChatRecordMapper, ChatRecord> implements ChatRecordService {

    @Resource
    private ChatRecordMapper chatRecordMapper;

    @Resource
    private UserBehaviorMapper userBehaviorMapper;

    @Autowired
    private VideoTransaction videoTransaction;

    @Override
    public String sendComment(ChatRecord chatRecord) throws Exception {

        String chatId = null;
        try{
            chatId = GenerateNum.generateOrder();
            chatRecord.setChatId(chatId);

            chatRecord.setSendTime(new Date());

            //保存一份数据到用户行为表
            UserBehavior userBehavior = new UserBehavior();
            userBehavior.setComment(true);
            userBehavior.setKeyId(chatId);
            userBehavior.setUserId(chatRecord.getUserId());
            userBehavior.setBehaviorTime(new Date());
            userBehavior.setBehaviorType(0);

            videoTransaction.execute(() -> {
                this.save(chatRecord);
                userBehaviorMapper.insert(userBehavior);
            });

        }catch (Exception e){
            e.printStackTrace();
            log.error("插入数据库错误,{}",e.getCause());
            throw e;
        }

        return chatId;
    }

    @Override
    @FormatFileURL(value = {"avatar"})
    public List<Map<String, Object>> getCommentList(CommentPage page) throws Exception {

        List<Map<String, Object>> commentList = new ArrayList<>();

        if(page.getVideoId() == null){

            log.error("传入videoId为空");

            throw new GlobalException(ResponseData.error("传入videoId为空"));
        }

        try{
            Field field = ChatRecord.class.getDeclaredField(page.getSortField());

            page.setSortField(StringUtil.cameToUnderline(page.getSortField()));

            commentList = chatRecordMapper.getCommentList(page);

        }catch (Exception e){
            e.printStackTrace();
            log.error("传入数据排序列错误");
            throw new GlobalException(ResponseData.error("传入数据排序列错误"));
        }

        return commentList;
    }

    @Override
    @FormatFileURL(value = {"avatar"} , type = CommentPage.class)
    public CommentPage getSubCommentList(CommentPage page) throws Exception {

        if(page.getVideoId() == null){

            log.error("传入videoId为空");

            throw new GlobalException(ResponseData.error("传入videoId为空"));
        }

        if(page.getParentId() == null){

            log.error("传入parentId为空");

            throw new GlobalException(ResponseData.error("传入parentId为空"));
        }

        try{
            Field field = ChatRecord.class.getDeclaredField(page.getSortField());

            page.setSortField(StringUtil.cameToUnderline(page.getSortField()));
            page.setList(chatRecordMapper.getSubCommentList(page));

            if(page.getTotal() <= 0){
                page.setTotal(chatRecordMapper.getSubCount(page));
            }

        }catch (Exception e){
            e.printStackTrace();
            log.error("传入数据排序列错误");
            throw new GlobalException(ResponseData.error("传入数据排序列错误"));
        }

        return page;
    }

    @Override
    public void agree(Map<String, Object> info) throws Exception {
        if(info.get("chatId") == null || info.get("num") == null){
            return ;
        }

        String userId = UserInfoUtils.getUserInfo().get("userId").toString();
        Map<String, Object> map = new HashMap<String, Object>(){{
            put("keyId",info.get("chatId").toString());
            put("agree",1);
            put("disagree",0);
            put("userId",userId);
            put("behaviorTime",new Date());
        }};

        videoTransaction.execute(()-> {
            chatRecordMapper.like(info);
            userBehaviorMapper.updateUserBehavior(map);
        });

    }

    @Override
    public void disagree(Map<String, Object> info) throws Exception {
        if(info.get("chatId") == null || info.get("num") == null){
            return ;
        }

        String userId = UserInfoUtils.getUserInfo().get("userId").toString();
        Map<String, Object> map = new HashMap<String, Object>(){{
            put("keyId",info.get("chatId").toString());
            put("agree",0);
            put("disagree",1);
            put("userId",userId);
            put("behaviorTime",new Date());
        }};
        videoTransaction.execute(()-> {
            chatRecordMapper.disagree(info);
            userBehaviorMapper.updateUserBehavior(map);
        });
    }
}
